package cmd

import (
	"context"
	"mini-upload/internal/controller/upload"
	"mini-upload/internal/dao"
	"os"

	"github.com/marcellowy/go-common/gogf/middleware"
	"github.com/marcellowy/go-common/gogf/vconfig"
	"github.com/marcellowy/go-common/gogf/vlog"
	"github.com/marcellowy/go-common/vid/snowflake"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			//
			if err = snowflake.Init(1); err != nil {
				vlog.Warning(ctx, err)
				return
			}

			// connect db
			if err = dao.Connect(ctx); err != nil {
				vlog.Warning(ctx, err)
				return
			}

			// start server
			s := g.Server()
			savePath := vconfig.Get("upload.savePath").String()
			if _, err = os.Stat(savePath); err != nil {
				if !os.IsNotExist(err) {
					vlog.Warning(ctx, err)
					return
				}
				if err = os.MkdirAll(savePath, os.ModePerm); err != nil {
					vlog.Warning(ctx, err)
					return
				}
			}
			s.BindHookHandler("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) {
				//r.Response.CORSDefault()
			})
			s.SetServerRoot(savePath)
			s.SetServerAgent("mini upload server")
			s.BindMiddlewareDefault(middleware.PrintResponse)
			s.Group("/api", func(group *ghttp.RouterGroup) {
				group.Middleware(ghttp.MiddlewareHandlerResponse)
				group.Middleware(ghttp.MiddlewareCORS)
				group.Middleware(middleware.PrintRequest)
				group.Bind(
					upload.NewV1(),
				)
			})
			s.Run()
			return nil
		},
	}
)
